﻿using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace FolderBrowser
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // 选择文件夹按钮点击事件
        private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                string selectedPath = dialog.SelectedPath;
                SelectedPathText.Text = selectedPath;
                LoadFolderStructure(selectedPath);
            }
        }

        // 加载文件夹结构到TreeView
        private void LoadFolderStructure(string path)
        {
            try
            {
                FolderTreeView.Items.Clear();
                var rootItem = CreateFolderItem(path);
                FolderTreeView.Items.Add(rootItem);
                rootItem.IsExpanded = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载文件夹时出错: {ex.Message}");
            }
        }

        // 递归添加子文件夹和文件项
        private FolderItem CreateFolderItem(string path)
        {
            var item = new FolderItem
            {
                Name = System.IO.Path.GetFileName(path) ?? path,
                FullPath = path,
                IsDirectory = true
            };

            try
            {
                // 添加子文件夹
                foreach (var dir in Directory.GetDirectories(path))
                {
                    item.Children.Add(CreateFolderItem(dir));
                }

                // 添加文件
                foreach (var file in Directory.GetFiles(path))
                {
                    item.Children.Add(new FolderItem
                    {
                        Name = System.IO.Path.GetFileName(file),
                        FullPath = file,
                        IsDirectory = false
                    });
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 无权限访问的文件夹，忽略
            }

            return item;
        }

        // 处理选中项变化事件
        private void FolderTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is FolderItem selectedItem && !selectedItem.IsDirectory)
            {
                HintWords.Visibility = Visibility.Collapsed;
                DisplayFileInfo(selectedItem.FullPath);
            }
            else
            {
                HintWords.Visibility = Visibility.Visible;
                FileDetailsPanel.Visibility = Visibility.Collapsed;
            }
        }

        private void DisplayFileInfo(string filePath)
        {
            try
            {
                var fileInfo = new FileInfo(filePath);

                // 设置文件图标(右侧详情页)
                var icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
                if (icon != null)
                {
                    FileIcon.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                        icon.Handle,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());

                    // 释放图标句柄，防止内存泄漏
                    NativeMethods.DestroyIcon(icon.Handle);
                }

                // 设置文件信息
                FileName.Text = fileInfo.Name;
                FilePath.Text = fileInfo.FullName;
                FileSize.Text = FormatFileSize(fileInfo.Length);
                FileCreated.Text = fileInfo.CreationTime.ToString();
                FileModified.Text = fileInfo.LastWriteTime.ToString();
                FileAccessed.Text = fileInfo.LastAccessTime.ToString();
                FileType.Text = fileInfo.Extension.ToUpper() + " 文件";
                FileAttributes.Text = fileInfo.Attributes.ToString();

                FileDetailsPanel.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"读取文件信息时出错: {ex.Message}");
            }
        }

        // 简单格式化文件大小
        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB", "TB" };
            int order = 0;
            double len = bytes;
            while (len >= 1024 && order < sizes.Length - 1)
            {
                order++;
                len = len / 1024;
            }
            return $"{len:0.##} {sizes[order]}";
        }
    }

    public class FolderItem
    {
        public string Name { get; set; } = "";
        public string FullPath { get; set; } = "";
        public bool IsDirectory { get; set; }
        public List<FolderItem> Children { get; set; } = new List<FolderItem>();
        public bool IsExpanded { get; set; }

        //先简单使用一个系统图标
        //public ImageSource Icon
        //{
        //    get
        //    {
        //        System.Drawing.Icon icon = IsDirectory ?
        //            System.Drawing.SystemIcons.Information :
        //            System.Drawing.SystemIcons.Application;

        //        return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
        //            icon.Handle,
        //            Int32Rect.Empty,
        //            BitmapSizeOptions.FromEmptyOptions());
        //    }
        //}

        // 使用本地资源图标
        public ImageSource Icon
        {
            get
            {
                string iconPath = IsDirectory ? "Assets/folder.png" : "Assets/file.png";
                return new BitmapImage(new Uri($"pack://application:,,,/{iconPath}"));
            }
        }

        public override string ToString() => Name;
    }

    internal static class NativeMethods
    {
        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        public static extern bool DestroyIcon(IntPtr hIcon);
    }
}